#coding:utf-8
'''view'''

from django.shortcuts import redirect, render
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.contrib import auth
from django.http import HttpResponse

def index(request):
    
    return render(request, 'index.html', {})

def sign_up(request):
	'''
		register a user
	'''
	error = ""
	if request.method == "POST":
		username = request.POST.get('username')
		password = request.POST.get('password')
		dopassword = request.POST.get('dopassword')

		# 用户名不为空 and 用户是否已存在
		try:
			exist = User.objects.get(username=username)
		except User.DoesNotExist:
			exist = ""
		if username != "" and not exist:
			# 密码不为空 and 密码是否一致
			if password != "" and password == dopassword:
				User.objects.create_user(username=username, password=password)
				return render(request, "account/sign_in.html", {"error" : error})

		error = "User exits or Password Error"
		return render(request, "account/sign_up.html", {"error" : error})

	return render(request, "account/sign_up.html", {"error" : error})

def sign_in(request):
	'''	
		login
	'''
	error = ""
	if request.method == "POST":
		username = request.POST.get('username')
		password = request.POST.get('password')
		user = auth.authenticate(username=username, password=password)

		if isinstance(user, User):
			auth.login(request, user)
			return redirect('/index')

		error = "User Does Not Exist Or Password Error."
		return render(request, 'account/sign_in.html', {'error' : error})

 	return render(request, 'account/sign_in.html', {'error' : error})

@login_required(login_url='sign_in')
def sign_out(request):
	print request
	auth.logout(request)
	return HttpResponse("Logout Success");
